package com.ipan.poi.excel.exporter;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ipan.poi.excel.config.XlsEntity;
import com.ipan.poi.excel.config.XlsProperty;
import com.ipan.poi.excel.util.XlsUtils;
import com.ipan.poi.jdbc.JDBCManager;

/**
 * 写入操作工具类
 * 
 * @author iPan
 * @version 2013-09-20
 */
public final class WriterUtils {
	
	protected static Logger logger = LoggerFactory.getLogger(WriterUtils.class);
	
	private WriterUtils() {}
	
	/**
	 * 添加标题信息；
	 * @return 下一行的位置
	 */
	public static int appendTitle(XlsEntity defEntity, Sheet sheet, CellStyleCreatable style, int curRowIndex) {
		List<XlsProperty> fields = defEntity.getProperties();
		if (fields == null || fields.size() < 1) {
			return curRowIndex;
		}
		Row row = sheet.createRow(curRowIndex);
		for (int cellIndex=0, len=fields.size(); cellIndex<len; ++cellIndex) {
			String title = fields.get(cellIndex).getTitle();
//			Cell cell = row.createCell(cellIndex, Cell.CELL_TYPE_STRING);
			Cell cell = row.createCell(cellIndex, CellType.STRING);
			cell.setCellValue(title);
			cell.setCellStyle(style.createTitleStyle(sheet.getWorkbook()));
		}
		return curRowIndex + 1;
	}

	/**
	 * 添加正文信息，根据实体类；
	 * @return 下一行的位置
	 */
	public static int appendBodyByEntity(XlsEntity defEntity, List<?> entityList, Sheet sheet, 
			CellStyleCreatable style, int curRowIndex) {
		List<XlsProperty> fields = defEntity.getProperties();
		if (fields == null || fields.size() < 1 || entityList == null || entityList.size() < 1) {
			return curRowIndex;
		}
		int rowIndex = curRowIndex;
		int endIndex = curRowIndex + entityList.size();
		for (; rowIndex<endIndex; ++rowIndex) {
			Row row = sheet.createRow(rowIndex);
			Object entity = entityList.get(rowIndex - curRowIndex);
			// 写入一行
			for (int cellIndex=0, len=fields.size(); cellIndex<len; ++cellIndex) {
				String name = fields.get(cellIndex).getName();
				String pattern = fields.get(cellIndex).getPattern(); // 自定义格式
				XlsUtils.createCellByEntity(entity, name, pattern, row, cellIndex, style.createBodyStyle(sheet.getWorkbook(), pattern));
			}
		}
		return rowIndex;
	}
	
	/**
	 * 添加正文信息，根据Map；
	 * @return 下一行的位置
	 */
	public static int appendBodyByMap(XlsEntity defEntity, List<Map<String, Object>> list, Sheet sheet, 
			CellStyleCreatable style, int curRowIndex) {
		List<XlsProperty> fields = defEntity.getProperties();
		if (fields == null || fields.size() < 1 || list == null || list.size() < 1) {
			return curRowIndex;
		}
		int rowIndex = curRowIndex;
		int endIndex = curRowIndex + list.size();
		for (; rowIndex<endIndex; ++rowIndex) {
			Row row = sheet.createRow(rowIndex);
			Map<String, ?> rowMap = list.get(rowIndex - curRowIndex);
			// 写入一行
			for (int cellIndex=0, len=fields.size(); cellIndex<len; ++cellIndex) {
				String name = fields.get(cellIndex).getName();
				String pattern = fields.get(cellIndex).getPattern();
				Object value = rowMap.get(name);
				Class<?> fieldType = defEntity.getPropertyType(name);
				XlsUtils.createCell(value, pattern, row, cellIndex, fieldType, style.createBodyStyle(sheet.getWorkbook(), pattern));
			}
		}
		return rowIndex;
	}
	
	/**
	 * 添加正文信息，根据JDBC结果集；
	 * @return 下一行的位置
	 */
	public static int appendBodyByResultSet(XlsEntity defEntity, ResultSet resultSet, Sheet sheet, 
			CellStyleCreatable style, int curRowIndex) {
		List<XlsProperty> fields = defEntity.getProperties();
		if (fields == null || fields.size() < 1 || resultSet == null) {
			return curRowIndex;
		}
		int rowIndex = curRowIndex;
		try {
			while(resultSet.next()) {
				Row row = sheet.createRow(rowIndex);
				// 写入一行
				for (int cellIndex=0, len=fields.size(); cellIndex<len; ++cellIndex) {
					String name = fields.get(cellIndex).getName();
					String pattern = fields.get(cellIndex).getPattern();
					Object value = null;
					try {
						value = resultSet.getObject(name);
					} catch (SQLException e) {
						logger.warn("获取实体[{}]设置属性[{}]出错！", defEntity.getClassName(), name);
					}
					Class<?> fieldType = defEntity.getPropertyType(name);
					XlsUtils.createCell(value, pattern, row, cellIndex, fieldType, style.createBodyStyle(sheet.getWorkbook(), pattern));
				}
				rowIndex++;
			}
		} catch (SQLException e) {
			JDBCManager.throwJDBCException(e);
		}
		return rowIndex;
	}
	
	/**
	 * 导出字段过滤
	 * 传入要导出的字段，这些字段必须在配置文件里面定义过；
	 * 返回过滤后的配置实体XlsEntity；
	 */
	public static XlsEntity getFilterXlsEntity(XlsEntity srcEntity, String[] needFields) {
		if (needFields == null || needFields.length < 1) {
			throw new RuntimeException("未提供需要导出的字段名称！");
		}
		XlsEntity newEntity = null;
		try {
			newEntity = srcEntity.clone();
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException("复制DefEntity实体出错！", e);
		}
		// 过滤需要的字段
		List<XlsProperty> curFields = newEntity.getProperties();
		List<XlsProperty> newFields = new ArrayList<XlsProperty>();
		for (String field : needFields) {
			for (XlsProperty defField : curFields) {
				if (defField.getName().equals(field)) {
					newFields.add(defField);
				}
			}
		}
		newEntity.setProperties(newFields);
		return newEntity;
	}

}
